use super::{PlantingUiState, component::*, resource::*};
use bevy::{color::palettes::css::*, prelude::*};

pub fn init_ui(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    backpack: ResMut<MasterBackpack>,
) {
    let font = asset_server.load("fonts/fusion-pixel.ttf");
    let font_size = 20.0;

    //农场时间信息文本
    commands
        .spawn((
            PlantingTimer(Timer::from_seconds(0.5, TimerMode::Repeating)),
            PlantingDayInfoText,
            Text::new("时间:"),
            TextFont {
                font: font.clone(),
                font_size: 30.0,
                ..default()
            },
            TextColor(Color::srgba(
                0.0 as f32 / u8::MAX as f32,
                111.0 as f32 / u8::MAX as f32,
                255.0 as f32 / u8::MAX as f32,
                1.0,
            )),
            Node {
                position_type: PositionType::Absolute,
                top: Val::Px(12.0),
                left: Val::Px(12.0),
                ..default()
            },
        ))
        .with_children(|p| {
            p.spawn(create_text_span(
                &font,
                30.0,
                String::default(),
                255,
                214,
                34,
                1.0,
            ));
        });

    //快捷栏文本信息
    commands
        .spawn((
            FastListInfoText,
            Text::new("-------快捷栏(V)-------\n"),
            TextFont {
                font: font.clone(),
                font_size,
                ..default()
            },
            TextColor(Color::srgba(
                0.0 as f32 / u8::MAX as f32,
                111.0 as f32 / u8::MAX as f32,
                255.0 as f32 / u8::MAX as f32,
                1.0,
            )),
            Node {
                position_type: PositionType::Absolute,
                bottom: Val::Px(10.0),
                left: Val::Px(12.0),
                ..default()
            },
        ))
        .with_children(|p| {
            for i in 0..9 {
                p.spawn(create_text_span(
                    &font,
                    font_size,
                    format!("{}: ", i + 1),
                    0,
                    111,
                    255,
                    1.0,
                ));
                p.spawn(create_text_span(
                    &font,
                    font_size,
                    format!("{:<10}", "空"),
                    255,
                    40,
                    171,
                    1.0,
                ));
                p.spawn(create_text_span(
                    &font,
                    font_size,
                    format!("\n"),
                    255,
                    214,
                    34,
                    1.0,
                ));
            }
            p.spawn(create_text_span(
                &font,
                font_size,
                format!("--------------------"),
                0,
                111,
                255,
                1.0,
            ));
        });

    //背包文本信息
    commands
        .spawn((
            BagInfoText,
            Text::new("--------背包(B)-------\n"),
            TextFont {
                font: font.clone(),
                font_size,
                ..default()
            },
            TextColor(Color::srgba(
                0.0 as f32 / u8::MAX as f32,
                111.0 as f32 / u8::MAX as f32,
                255.0 as f32 / u8::MAX as f32,
                1.0,
            )),
            Node {
                position_type: PositionType::Absolute,
                bottom: Val::Px(10.0),
                right: Val::Px(12.0),
                ..default()
            },
        ))
        .with_children(|p| {
            for i in 0..backpack.show_count {
                p.spawn(create_text_span(
                    &font,
                    font_size,
                    format!("{}: ", i + 1),
                    0,
                    111,
                    255,
                    1.0,
                ));
                p.spawn(create_text_span(
                    &font,
                    font_size,
                    format!("{}", "空"),
                    255,
                    40,
                    171,
                    1.0,
                ));
                p.spawn(create_text_span(
                    &font,
                    font_size,
                    format!("\n"),
                    255,
                    214,
                    34,
                    1.0,
                ));
            }
            p.spawn(create_text_span(
                &font,
                font_size,
                format!("--------------------"),
                0,
                111,
                255,
                1.0,
            ));
        });
}

///创建TextSpan
pub fn create_text_span(
    font: &Handle<Font>,
    font_size: f32,
    text: String,
    r: u8,
    g: u8,
    b: u8,
    a: f32,
) -> impl Bundle {
    (
        TextSpan::new(text),
        TextColor(Color::srgba(
            r as f32 / u8::MAX as f32,
            g as f32 / u8::MAX as f32,
            b as f32 / u8::MAX as f32,
            a,
        )),
        TextFont {
            font: font.clone(),
            font_size,
            ..default()
        },
    )
}

///更新快捷栏信息
pub fn updata_last_info(
    query: Single<Entity, With<FastListInfoText>>,
    goods_list: Res<FastList>,
    ui_state: Res<State<PlantingUiState>>,
    goods_query: Query<(&FastListIndexComponent, Option<&GoodsComponent>)>, //获取物品信息
    mut text_writer: TextUiWriter,
) {
    let select_index = goods_list.select_index;
    let mut select_str = "<==";
    if *ui_state.get() == PlantingUiState::FastList {
        *text_writer.text(*query, 28) = format!("(空格键)取消快捷栏(E)整理");
    } else {
        *text_writer.text(*query, 28) = format!("--------------------");
        select_str = "";
    }

    goods_query.iter().for_each(|(index, item)| {
        let index = index.index;
        if let Some(item) = item {
            *text_writer.text(*query, index * 3 + 2) =
                format!("{} x {}", item.goods_item, item.count);
        } else {
            *text_writer.text(*query, index * 3 + 2) = format!("{}", "空");
        }
        if index == select_index {
            *text_writer.text(*query, index * 3 + 3) = format!("{}\n", select_str);
        } else {
            *text_writer.text(*query, index * 3 + 3) = format!("\n");
        }
    });
}

///更新背包信息
pub fn updata_bag_info(
    query: Single<Entity, With<BagInfoText>>,
    backpack: Res<MasterBackpack>,
    ui_state: Res<State<PlantingUiState>>,
    goods_query: Query<(&BackpackIndexComponent, Option<&GoodsComponent>)>, //获取物品信息
    mut text_writer: TextUiWriter,
) {
    let mut select_str = "<==";
    if *ui_state.get() == PlantingUiState::Backpack {
        *text_writer.text(*query, 28) = format!("(空格键)装备快捷栏(E)整理");
    } else {
        *text_writer.text(*query, 28) = format!("--------------------");
        select_str = "";
    }
    goods_query.iter().for_each(|(index, item)| {
        let curr_index = index.index;
        if curr_index < backpack.offset || curr_index >= backpack.offset + backpack.show_count {
            return;
        }
        let index = curr_index - backpack.offset;
        *text_writer.text(*query, index * 3 + 1) = format!("{:>2}: ", curr_index + 1);
        if let Some(item) = item {
            *text_writer.text(*query, index * 3 + 2) =
                format!("{} x {}", item.goods_item, item.count);
        } else {
            *text_writer.text(*query, index * 3 + 2) = format!("{}", "空");
        }
        if index == backpack.select_index {
            *text_writer.text(*query, index * 3 + 3) = format!("{}\n", select_str);
        } else {
            *text_writer.text(*query, index * 3 + 3) = format!("\n");
        }
    });
}

///更新农场时间信息
pub fn updata_planting_day_info(
    query: Single<Entity, With<PlantingDayInfoText>>,
    planting_day: Res<PlantingDay>,
    mut text_writer: TextUiWriter,
) {
    *text_writer.text(*query, 1) =
        format!(" {} - {}", planting_day.day, planting_day.get_time_str());
}

pub fn spawn_bottom_ui(
    mut commands: Commands,
    goods_query: Query<(&FastListIndexComponent, Option<&GoodsComponent>)>,
    asset_server: Res<AssetServer>,
) {
    let font = asset_server.load("fonts/fusion-pixel.ttf");
    commands
        .spawn(Node {
            width: Val::Percent(100.0),
            height: Val::Percent(100.0),
            align_items: AlignItems::End,
            justify_content: JustifyContent::Center,
            ..default()
        })
        .insert(Pickable::IGNORE)
        .with_children(|parent| {
            parent
                .spawn((
                    Node {
                        flex_direction: FlexDirection::Row,
                        align_items: AlignItems::Center,
                        column_gap: Val::Px(5.0),
                        ..default()
                    },
                    BackgroundColor(DIM_GRAY.into()),
                ))
                .insert(Pickable::IGNORE)
                .with_children(|parent| {
                    let icon = asset_server.load("texture/ui/goods_from.png");
                    let mut goods_query = goods_query.iter().collect::<Vec<_>>();
                    goods_query.sort_by(|a, b| a.0.index.cmp(&b.0.index));
                    goods_query.iter().for_each(|(index, item)| {
                        let index = index.index;
                        let mut entity = parent.spawn((
                            FastListButton { index },
                            Button,
                            ImageNode::new(icon.clone()),
                            Node {
                                height: Val::Px(80.0),
                                width: Val::Px(80.0),
                                justify_content: JustifyContent::Center,
                                align_items: AlignItems::Center,
                                ..default()
                            },
                        ));
                        let mut str = "空".to_string();
                        if let Some(item) = item {
                            str = item.goods_item.to_string() + &format!("\n{}", item.count);
                        }
                        entity.with_children(|parent| {
                            parent.spawn((
                                Text::new(str),
                                TextFont {
                                    font: font.clone(),
                                    font_size: 16.0,
                                    ..default()
                                },
                                TextLayout::new_with_justify(JustifyText::Center),
                            ));
                        });
                    });
                });
        });
}

///更新快捷栏
pub fn updata_bottom_last_ui_color(
    mut query: Query<(&mut ImageNode, &Interaction, &FastListButton), With<Interaction>>, //获取物品信息
    goods_list: Res<FastList>,
) {
    query
        .iter_mut()
        .for_each(|(mut image, interaction, btn_index)| match interaction {
            Interaction::Pressed => {
                image.color = INDIAN_RED.into();
            }
            Interaction::Hovered => {
                image.color = YELLOW_GREEN.into();
            }
            Interaction::None => {
                if goods_list.select_index == btn_index.index {
                    image.color = GOLD.into();
                } else {
                    image.color = WHEAT.into();
                }
            }
        });
}
